# ！/usr/bin/python3
# -*- coding:utf-8 -*-

"""
@author: hou
@time: 2024/11/28
模块注释：
    七牛云接口
"""
import os
import uuid

from qiniu import Auth, put_file
from config import get_kodo_key, get_kodo_bucket, get_logo_path
import qrcode
from PIL import Image



def kodo_upload(key, file_path, progress_handler, expires=3600):
    """
        图片上传
    :param progress_handler: 进度回调
    :param key: 上传文件名称，带云路径
    :param file_path: 上传文件的路径
    :param expires: 上传凭证过期时间
    :return:
    """
    access_key, secret_key = get_kodo_key()
    bucket_name, bucket_domain = get_kodo_bucket()

    q = Auth(access_key, secret_key)

    token = q.upload_token(bucket_name, key, expires)

    ret, info = put_file(token, key, file_path, version='v2', progress_handler=progress_handler)

    if info.status_code == 200:
        # 生成公开访问链接
       return 0, f'{bucket_domain}/{ret["key"]}'


    return 1, f'上传失败，错误信息：{info.text}'



def generate_qr(data, is_logo=False, output_size=300):
    # 创建二维码对象
    qr = qrcode.QRCode(
        version=4,
        error_correction=qrcode.constants.ERROR_CORRECT_M,
        box_size=10,
        border=4
    )
    qr.add_data(data)
    qr.make(fit=True)

    # 生成基础二维码图像
    qr_img = qr.make_image(fill_color="black", back_color="white").convert('RGBA')

    if is_logo:
        logo_path = get_logo_path()
        if logo_path:
            # 打开并处理LOGO
            logo = Image.open(logo_path).convert('RGBA')

            # 创建一个白色背景的相同尺寸画布
            white_bg = Image.new("RGB", logo.size, (255, 255, 255))

            # 将LOGO粘贴到白色背景上（保留透明度）
            white_bg.paste(logo, (0, 0), logo)  # 第三个参数是遮罩（mask）

            logo_size = int(output_size / 3)  # LOGO大小为二维码的1/4
            logo = white_bg.resize((logo_size, logo_size), Image.LANCZOS)

            # 计算粘贴位置
            pos = ((qr_img.size[0] - logo.size[0]) // 2,
                   (qr_img.size[1] - logo.size[1]) // 2)

            # 创建遮罩并合成图像
            qr_img.paste(logo, pos)
    qr_img.resize((output_size, output_size), Image.LANCZOS)
    unique_id = uuid.uuid4()
    if not os.path.exists("qrcode"):
        os.mkdir("qrcode")
    file = f"qrcode/{unique_id}.png"
    qr_img.save(file)
    return file


def clear_directory(directory_path):
    """
    删除指定目录下的所有文件
    :param directory_path: 目标目录路径
    """
    if not os.path.exists(directory_path):
        print(f"错误：目录 '{directory_path}' 不存在。")
        return False

    if not os.path.isdir(directory_path):
        print(f"错误：'{directory_path}' 不是一个有效的目录。")
        return False

    try:
        for root, dirs, files in os.walk(directory_path, topdown=False):
            for name in files:
                file_path = os.path.join(root, name)
                os.remove(file_path)
        return True
    except Exception as e:
        print(f"删除目录下所有文件时发生错误: {e}")
        return False



if __name__ == '__main__':
    logo = "logo.png"
    generate_qr("https://xyzk.tianshujiaoyu.com", logo)
